package pais.www.stat;

import java.io.PrintWriter;
import java.util.StringTokenizer;

import pais.db.*;
import papos.rowset.KeyNameNotFoundException;
import papos.rowset.StorageSystem;
import pasys.error.PaposException;

class PrintUrlKeys {
  public static final int KEYWORD_COUNT_PER_LINE = 10;

  public static void printPageKeywords(PrintWriter toClient, StringTokenizer stok) throws PaposException  {
    int uid = 0;
    if (stok.hasMoreTokens()) {
      String UidOrUrl = stok.nextToken();
      try {
        uid = Integer.parseInt(UidOrUrl);
        printUidKeywords(toClient, uid);
      } catch (NumberFormatException e) {
        printUrlKeywords(toClient, UidOrUrl);
      }
    } else {
      Commands.printStatUsage(toClient);
    }
  }

  private static void printUrlKeywords(PrintWriter toClient, String url) throws PaposException  {
    HtmlPage page = HtmlPageTable.getInstance().getPage(url);
    if (page == null) {
      toClient.println("No such url => " + url);
    } else {
      PrintUrl.printURLSummary(toClient, page);
      printHtmlPageKeywords(toClient, page.getUID());
    }
  }

  private static void printUidKeywords(PrintWriter toClient, long uid) throws PaposException  {
    HtmlPage page = HtmlPageTable.getInstance().getPage(uid);
    if (page == null) {
      toClient.println("No such url => " + uid);
    } else {
      PrintUrl.printURLSummary(toClient, page);
      printHtmlPageKeywords(toClient, uid);
    }
  }

  private static void printHtmlPageKeywords(PrintWriter toClient, long uid) throws PaposException  {

    KeywordTable keywordTable = KeywordTable.getInstance();
    Keyword kw = new Keyword();
    StorageSystem storage = keywordTable.getStorage();
    int count = 0;
    try {
      kw.setUID(uid);
      if (storage.find("UID_", kw)) {
        do {
          if(kw.getUID() != uid) {
            break;
          }
          toClient.print("&lt;" + kw.getKeyword() + "&gt;");
          if ( (count ++ % KEYWORD_COUNT_PER_LINE) == 0 ) 
            toClient.println("<br>");

        } while (storage.findNext("UID_", kw));
      }
    } catch (KeyNameNotFoundException e) {
      assert(false);
    }
  }

}
